package net.studou.interceptor;

import net.studou.action.BasicAction;
import net.studou.exception.SecretException;
import net.studou.vo.VUser;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionInvocation;

public class SecretLog {

	public static final String JSON = "Json";
	public static final String NORMAL = "";

	public static String log(ActionInvocation invocation, Logger log, SecretException e) {
		BasicAction basicAction = (BasicAction) invocation.getAction();
		String result = "error";
		log.error("Secret exception", e);
		if (e != null) {
			log.error("============================================================");
			switch (e.getType()) {
			case SecretException.GET_FIELD_ERROR:
				SecretLog.logGetFieldError(log, e);
				break;
			case SecretException.ENCRYPT_DECRYPT_ERROR:
				SecretLog.logEncryptAndDecryptError(log, e);
				break;
			case SecretException.SET_STATUS_ERROR:
				SecretLog.logSetStatusError(log, e);
				break;
			case SecretException.SIGNATURE_ERROR:
				SecretLog.logSignatureError(log, e);
				break;
			default:
				break;
			}
			log.error("============================================================");
		}

		String userName = null;
		if (basicAction.getSession().getAttribute("userInfo") == null) {
			if (basicAction.getUser() != null) {
				userName = basicAction.getUser().getUserName();
			}
		} else {
			userName = ((VUser) basicAction.getSession().getAttribute("userInfo")).getUserName();
		}

		try {
			if (userName != null) {
				if(SecretException.USER_LOCKED != e.getType()){
					basicAction.getUserService().lockUser(userName);
				}
				result = "lock";
			}
		} catch (Exception e1) {
			result = "error";
			log.error("Lock user exception", e1);
		}
		return result;
	}

	private static void logGetFieldError(Logger log, SecretException e) {
		log.error(e.getPo());
		log.error(e.getField().getName());
	}

	private static void logSetStatusError(Logger log, SecretException e) {
		log.error(e.getPo());
		log.error(e.getField().getName());
		log.error(e.getOperateValue());
	}

	private static void logEncryptAndDecryptError(Logger log, SecretException e) {
		log.error(e.getPo());
		log.error(e.getField().getName());
		log.error(e.getKey());
		log.error(e.getOperateValue());
	}

	private static void logSignatureError(Logger log, SecretException e) {
		log.error(e.getPo());
		log.error(e.getField().getName());
		log.error(e.getKey());
		log.error(e.getRealValue());
		log.error(e.getOperateValue());
	}
}
